package service

import (
	"cangqiong-takeout/src/common"
	"cangqiong-takeout/src/model"
	"cangqiong-takeout/src/utils"
	"github.com/asaskevich/govalidator"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func EmployeeUserLogin(c *gin.Context) {
	var us model.Employee
	if err := c.ShouldBindJSON(&us); err != nil {
		utils.ResponseBad(c, common.UserLoginBad, nil)
		return
	}
	pwd := us.PassWord
	if err := utils.MysqlDB.Table("employee").Where("username=?", us.UserName).First(&us).Error; err != nil {
		utils.ResponseBad(c, common.UserLoginBad, nil)
	}
	if !utils.ValidateMd5(pwd, common.PassWordMD5Key, us.PassWord) {
		utils.ResponseBad(c, common.LoginBadPwdError, nil)
		return
	}
	if us.Status == common.Disable {
		utils.ResponseBad(c, common.UserIsLocking, nil)
		return
	}
	var (
		token string
		err   error
	)
	get := utils.RedisHMGet(us.UserName, "token")
	if get != nil {
		token = get[0].(string)
		goto success
	}
	token, err = utils.NewToken(us.ID, us.UserName, us.PassWord)
	if err != nil || token == "" {
		utils.ResponseBad(c, common.SeverBad, nil)
		return
	}
	if err = utils.RedisDB.HMSet(utils.RedisContext, us.UserName, map[string]interface{}{
		"token": token,
		"name":  us.Name,
		"id":    us.ID,
		"phone": us.Phone,
	}).Err(); err != nil {
		utils.ResponseBad(c, common.SeverBad, nil)
		return
	}
	utils.RedisDB.Expire(utils.RedisContext, us.UserName, common.Day)
success:
	utils.ResponseSuccess(c, common.LoginSuccess, gin.H{
		"id":       us.ID,
		"name":     us.Name,
		"token":    token,
		"userName": us.UserName,
	})
}

func EmployeeUserLogout(c *gin.Context) {
	utils.ResponseSuccess(c, common.UserLogout, nil)
}

func AddEmployeeUser(c *gin.Context) {
	var us model.Employee
	if err := c.ShouldBindJSON(&us); err != nil {
		utils.ResponseBad(c, common.AddError, nil)
		return
	}
	if utils.StringEmpty(us.Phone, us.IdNumber, us.UserName, us.Name, us.Sex) {
		utils.ResponseBad(c, common.FormatError, nil)
		return
	}
	if ok, err := govalidator.ValidateStruct(&us); err != nil || !ok {
		utils.ResponseBad(c, common.ReError+",检查手机号和身份证格式是否正确", nil)
		return
	}
	var count int64
	utils.MysqlDB.Table("employee").Where("username=? OR id_number=? OR phone=?", us.UserName, us.IdNumber, us.Phone).Count(&count)
	if count > 0 {
		utils.ResponseBad(c, common.UserIsExistence, nil)
		return
	}
	createUserID := c.GetInt("userid")
	us.Status = common.Disable
	us.CreateTime = time.Now()
	us.PassWord = utils.NewMd5String(us.PassWord, common.PassWordMD5Key)
	us.CreateUser = createUserID
	us.UpdateUser = createUserID
	us.UpdateTime = time.Now()
	utils.MysqlDB.Table("employee").Create(&us)
	utils.ResponseSuccess(c, common.AddSuccess, nil)
}

func FindEmployeeUser(c *gin.Context) {
	searchUserName := c.Query("name")
	page, err := strconv.Atoi(c.Query("page"))
	sizeNumber, err := strconv.Atoi(c.Query("pageSize"))
	offset := (page - 1) * sizeNumber
	if err != nil {
		utils.ResponseBad(c, common.FormatError, nil)
		return
	}
	if searchUserName != "" {
		user, err, cnt := findUser(searchUserName, offset, sizeNumber)
		if err != nil {
			utils.ResponseBad(c, common.FindError, nil)
			return
		}
		if len(user) < 1 {
			utils.ResponseBad(c, common.ValueIsEmpty, nil)
			return
		}
		utils.ResponseSuccess(c, common.FindSuccess, gin.H{
			"total":   cnt,
			"records": user,
		})
		return
	}
	var (
		cnt int64
		us  []*model.Employee
	)
	if err = utils.MysqlDB.Table("employee").Count(&cnt).Limit(sizeNumber).Offset(offset).Find(&us).Error; err != nil {
		utils.ResponseBad(c, common.FindError, nil)
		return
	}
	for i := 0; i < len(us); i++ {
		us[i].EncryptionPwd("******")
		us[i].FormatCreateTimeFunc()
		us[i].FormatUpdateTimeFunc()
	}
	utils.ResponseSuccess(c, common.FindSuccess, gin.H{
		"total":   cnt,
		"records": us,
	})
}

func findUser(name string, offset int, sizeNumber int) ([]*model.Employee, error, int64) {
	var (
		us  []*model.Employee
		cnt int64
	)

	if err := utils.MysqlDB.Table("employee").Where("name like ?", "%"+name+"%").Count(&cnt).Limit(sizeNumber).Offset(offset).Find(&us).Error; err != nil {
		return nil, err, 0
	}
	for i := 0; i < len(us); i++ {
		us[i].EncryptionPwd("******")
		us[i].FormatCreateTimeFunc()
		us[i].FormatUpdateTimeFunc()
	}
	return us, nil, cnt
}

func FindEmployeeUserToID(c *gin.Context) {
	userID := c.Param("id")
	ID, err := strconv.Atoi(userID)
	if ID == 0 || err != nil {
		utils.ResponseBad(c, common.FormatError, nil)
		return
	}
	var us *model.Employee
	if err = utils.MysqlDB.Table("employee").Where("`id`=?", ID).First(&us).Error; err != nil {
		utils.ResponseBad(c, common.FindError, nil)
		return
	}
	us.FormatUpdateTimeFunc()
	us.FormatCreateTimeFunc()
	us.EncryptionPwd("******")
	utils.ResponseSuccess(c, common.FindSuccess, us)
}

func SetEmployeeUserStatus(c *gin.Context) {
	status := c.Param("status")
	id := c.Query("id")
	statusID, err := strconv.Atoi(status)
	userID, err := strconv.Atoi(id)
	if err != nil {
		utils.ResponseBad(c, common.ModifyError, nil)
		return
	}
	utils.MysqlDB.Table("employee").Where("`id`=?", userID).Update("status", statusID)
	utils.ResponseSuccess(c, common.ModifySuccess, nil)
}

func EditEmployeeUserMessage(c *gin.Context) {
	var us model.Employee
	if err := c.ShouldBindJSON(&us); err != nil {
		utils.ResponseBad(c, common.ModifyError, nil)
		return
	}
	if ok, err := govalidator.ValidateStruct(&us); err != nil || !ok {
		utils.ResponseBad(c, common.ReError+",检查数据是否合规", nil)
		return
	}
	if err := utils.MysqlDB.Table("employee").Where("`id`=?", us.ID).Updates(&us).Error; err != nil {
		utils.ResponseBad(c, common.ModifyError, nil)
		return
	}
	utils.ResponseSuccess(c, common.ModifySuccess, nil)
}

func EditEmployeePassWord(c *gin.Context) {
	var msg struct {
		NewPassword string `json:"newPassword"`
		OldPassword string `json:"oldPassword"`
	}
	id := c.GetInt("userid")
	if err := c.ShouldBindJSON(&msg); err != nil {
		utils.ResponseBad(c, common.ModifyError, nil)
		return
	}
	if msg.NewPassword == msg.OldPassword {
		utils.ResponseBad(c, "两次密码相等", nil)
		return
	}
	var us model.Employee
	if err := utils.MysqlDB.Table("employee").Where("`id`=?", id).First(&us).Error; err != nil {
		utils.ResponseBad(c, common.ModifyError, nil)
		return
	}
	if utils.NewMd5String(msg.NewPassword, common.PassWordMD5Key) == us.PassWord {
		utils.ResponseBad(c, "新密码与旧密码相等", nil)
		return
	}
	if utils.NewMd5String(msg.OldPassword, common.PassWordMD5Key) != us.PassWord {
		utils.ResponseBad(c, "旧密码不正确", nil)
		return
	}
	us.PassWord = utils.NewMd5String(msg.NewPassword, common.PassWordMD5Key)
	if err := utils.MysqlDB.Table("employee").Where("`id`=?", id).Update("password", us.PassWord).Error; err != nil {
		utils.ResponseBad(c, common.ModifyError, nil)
		return
	}
	utils.ResponseSuccess(c, common.ModifySuccess, nil)
}
